<template>
  <div class="loginContainer">
    <myHeader :head-title="loginWay? '短信登录':'密码登录xxx'" goBack="true">
      <div slot="changeLogin" class="change_login" @click="changeLoginWay">{{loginWay? "密码登录":"短信登录"}}</div>
    </myHeader>
    <form class="loginForm" v-if="loginWay">
      <section class="input_container phone_number">
        <input type="number" pattern="[0-9]*" placeholder="请输入手机号" name="phone" maxlength="11" v-model="mobileNo">
        <button @click.prevent="getVerifyCode" :class="{right_phone_number:rightMobileNo}" v-show="!computedTime">获取验证码</button>
        <button  @click.prevent v-show="computedTime">已发送({{computedTime}}s)</button>
      </section>
      <section class="input_container">
        <input type="text" placeholder="验证码" name="mobileCode" maxlength="6" v-model="mobileCode">
      </section>
    </form>
    <form class="loginForm" v-else>
      <section class="input_container">
        <input type="text" placeholder="账号/手机号" name="phone" maxlength="11" v-model.lazy="userAccount">
      </section>
      <section class="input_container">
        <input v-if="!showPassword" type="password" placeholder="密码"  v-model="passWord">
        <input v-else type="text" placeholder="密码"  v-model="passWord">
        <div class="button_switch" :class="{change_to_text: showPassword}">
          <div class="circle_button" :class="{trans_to_right: showPassword}" @click="changePassWordType"></div>
          <span>abc</span>
          <span>...</span>
        </div>
      </section>
<!--       <section class="input_container captcha_code_container">
        <input type="text" placeholder="验证码" maxlength="4" v-model="codeNumber">
        <div class="img_change_img">
          <img v-show="captchaCodeImg" :src="captchaCodeImg">
          <div class="change_img" @click="getCaptchaCode">
            <p>看不清</p>
            <p>换一张</p>
          </div>
        </div>
      </section> -->
    </form>
    <p class="login_tips">温馨提示：未注册过的账号，登录时将自动注册</p>
    <p class="login_tips">注册过的用户可凭账号密码登录</p>
    <div class="login_container" @click="userLogin">登录</div>
    <router-link to="/forget" class="to_forget" v-if="!loginWay">重置密码？</router-link>
    <alert-tip v-if="showAlert" :showHide="showAlert" @closeTip="closeTip" :alertText="alertText"></alert-tip>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import myHeader from '@/components/common/header/header'
  import alertTip from '@/components/common/alertTip'
  import {rsaEncStr} from '@/myutl/utlenc'
  import {getStore} from '@/config/mUtils'
  export default {
    data() {
      return {
        loginWay: false, //登录方式，默认短信登录
        showPassword: false, // 是否显示密码
        mobileNo: null,       // 手机号码
        mobileCode: null, //短信验证码
        validate_token: null, //获取短信时返回的验证值，登录时需要
        computedTime: 0, //倒数记时
        userInfo: null, //获取到的用户信息
        userAccount: null, //用户名
        passWord: null, //密码
        encLoginPwd: null,
        captchaCodeImg: null, //验证码地址
        codeNumber: null,   // 验证码
        showAlert: false,   // 显示提示组件
        alertText: null,    // 提示的内容
        pageRefresh: false 
      }
    },
    components:{
      myHeader,
      alertTip,
    },
    computed: {
      ...mapGetters([
        'storeUser',
        'coupons',
        'isActRet',
        'storeAuthInf'
      ]),
      rightMobileNo: function() {   // 判断手机号码
          return /^1\d{10}$/gi.test(this.mobileNo);
      },
      loginErrmsg: function() {
        return this.storeUser.loginErrmsg;
      },
      isLoginSucc: function() {
        return this.storeUser.isLoginSucc;
      }
    },
    mounted() {
      if (!this.storeAuthInf.authCode) {
        console.log("authCode is null: getAuthCode");
        this.$store.dispatch('getAuthCode');
      }
      if (this.storeAuthInf.authCode && !this.storeAuthInf.authToken) {
        console.log("authToken is null: getAuthToken");
        this.$store.dispatch('getAuthToken', this.storeAuthInf.authCode);
      }
      let storeUser = JSON.parse(getStore('storeUser'));
      if (storeUser) {
        this.userAccount = storeUser.id;
        this.encLoginPwd = storeUser.loginPwd;
        this.passWord = 'hasEncLoginPwd';
        console.log("encLoginPwd:", this.encLoginPwd);
      }
      this.getCaptchaCode();
    },
    methods: {
      changeLoginWay() {  // 改变登录方式
        this.loginWay = !this.loginWay;
      },
      changePassWordType() {    // 是否显示密码
        this.showPassword = !this.showPassword;
      },
      async getCaptchaCode() {  // 异步方式获取验证吗
          // let res = await getcaptchas();
          // this.captchaCodeImg = res.code;
      },
      async getVerifyCode() {   // 异步方式获取短信验证码
        if (this.rightMobileNo) {
          this.computedTime = 10;
          this.timer = setInterval(() => {
            this.computedTime --;
            if (this.computedTime == 0) {
                clearInterval(this.timer)
            }
          }, 1000);
          // 发送短信验证码
          // !!dispatch中有axios异步操作,需要后续特殊处理
          this.$store.dispatch('sendMobileCode', {
            templateNo: "5",      // 5=登陆并注册短信验证码发送
            mobileNo: this.mobileNo
          }).then(() => {   // 无法通过then获取正确的异步结果
            console.log("then:", this.isLoginSucc, this.isActRet);
          });
        }
      },
      async userLogin() {
        if (this.loginWay) {    // 手机验证码登陆
          if (!this.rightMobileNo) {
              this.showAlert = true;
              this.alertText = '手机号码不正确';
              return
          } else if(!(/^\d{6}$/gi.test(this.mobileCode))){
              this.showAlert = true;
              this.alertText = '短信验证码不正确';
              return
          }
          this.$store.dispatch('verifyCodeLogin', {
            loginName:this.mobileNo, 
            verifyCode:this.mobileCode
          }).then(() => {   // 无法通过then获取正确的异步结果
            console.log("then:", this.isLoginSucc, this.isActRet);
          });
        } else {    // 用户名密码登录
          if (!this.userAccount) {
            this.showAlert = true;
            this.alertText = '请输入手机号/邮箱/用户名';
            return;
          } else if (!this.passWord){
            this.showAlert = true;
            this.alertText = '请输入密码';
            return;
          }//else if (!this.codeNumber){
          //     this.showAlert = true;
          //     this.alertText = '请输入验证码';
          //     return
          // }
          let encPwd = null;
          if (this.passWord === 'hasEncLoginPwd') {
            encPwd = this.encLoginPwd;
          } else {
            // 对密码进行加密
            encPwd = rsaEncStr(this.passWord);
          }
          await this.$store.dispatch('login', {
            loginName: this.userAccount, 
            passWord: encPwd, 
            codeNumber: this.codeNumber
          });
        }

        if (!this.isLoginSucc) {  // 如果返回的值不正确，则弹出提示框
          this.showAlert = true;
          this.alertText = this.loginErrmsg?this.loginErrmsg:'登录超时请重试';
          this.pageRefresh = true;
          // if (!this.loginWay) this.getCaptchaCode();
        } else {  // 返回的值正确则返回上一页
          // this.RECORD_USERINFO(this.userInfo);
          // // console.log("this.$router.go('/profile')");
          this.$router.go(-1); // 返回上一页
          // ??无法返回指定页
          // this.$router.go('/profile');  
        }
      },
      closeTip() {
        this.showAlert = false;
        this.pageRefresh = false;
        this.$router.go(0);
      }
    },
    watch: {
      'storeAuthInf.authCode': function(val, oldVal) {
        // 重新获取code后需要再次获取token
        console.log("watch:authCode:", oldVal, val);
        this.$store.dispatch('getAuthToken', this.storeAuthInf.authCode);
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import 'src/style/mixin';

  .loginContainer{
      padding-top: 1.95rem;
      p, span, input{
          font-family: Helvetica Neue,Tahoma,Arial;
      }
  }
  .change_login{
      position: absolute;
      @include ct;
      right: 0.75rem;
      @include sc(.7rem, #fff);
  }
  .loginForm{
      background-color: #fff;
      margin-top: .6rem;
      .input_container{
          display: flex;
          justify-content: space-between;
          padding: .6rem .8rem;
          border-bottom: 1px solid #f1f1f1;
          input{
              @include sc(.7rem, #666);
          }
          button{
              @include sc(.65rem, #fff);
              font-family: Helvetica Neue,Tahoma,Arial;
              padding: .28rem .4rem;
              border: 1px;
              border-radius: 0.15rem;
          }
          .right_phone_number{
              background-color: #4cd964;
          }
      }
      .phone_number{
          padding: .3rem .8rem;
      }
      .captcha_code_container{
          height: 2.2rem;
          .img_change_img{
              display: flex;
              align-items: center;
              img{
                  @include wh(3.5rem, 1.5rem);
                  margin-right: .2rem;
              }
              .change_img{
                  display: flex;
                  flex-direction: 'column';
                  flex-wrap: wrap;
                  width: 2rem;
                  justify-content: center;
                  p{
                      @include sc(.55rem, #666);
                  }
                  p:nth-of-type(2){
                      color: #3b95e9;
                      margin-top: .2rem;
                  }
              }
          }
      }
  }
  .login_tips{
      @include sc(.5rem, red);
      padding: .4rem .6rem;
      line-height: .5rem;
      a{
          color: #3b95e9;
      }
  }
  .login_container{
      margin: 0 .5rem 1rem;
      @include sc(.7rem, #fff);
      background-color: #4cd964;
      padding: .5rem 0;
      border: 1px;
      border-radius: 0.15rem;
      text-align: center;
  }
  .button_switch{
      background-color: #ccc;
      display: flex;
      justify-content: center;
      @include wh(2rem, .7rem);
      padding: 0 .2rem;
      border: 1px;
      border-radius: 0.5rem;
      position: relative;
      .circle_button{
          transition: all .3s;
          position: absolute;
          top: -0.2rem;
          z-index: 1;
          left: -0.3rem;
          @include wh(1.2rem, 1.2rem);
          box-shadow: 0 0.026667rem 0.053333rem 0 rgba(0,0,0,.1);
          background-color: #f1f1f1;
          border-radius: 50%;
      }
      .trans_to_right{
          transform: translateX(1.3rem);
      }
      span{
          @include sc(.45rem, #fff);
          transform: translateY(.05rem);
          line-height: .6rem;
      }
      span:nth-of-type(2){
          transform: translateY(-.08rem);
      }
  }
  .change_to_text{
      background-color: #4cd964;
  }
  .to_forget{
      float: right;
      @include sc(.6rem, #3b95e9);
      margin-right: .3rem;
  }
</style>